package com.atsmart.app.sql;

import java.util.ArrayList;
import java.util.List;

import com.atsmart.app.model.ContextInfo;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

public class ContextSqlHelper {

	private SQLiteDatabase db = null;

	/**
	 * 打开数据库
	 */
	public void open(SqlHelper dh) {
		// dh = new SqlHelper(null, "atsmart", null,SqlHelper.getDBVersion());
		db = dh.getWritableDatabase();
	}

	public synchronized void addContextInfo(ContextInfo at) {
		if (at == null) {
			return;
		}
		String strSql = "insert or replace into context_info (context,type,name,date,imgpath,vediopath,recpath) values(?,?,?,?,?,?,?);";
		try {
			SQLiteStatement stm = db.compileStatement(strSql);
			stm.bindString(1, at.getContext());
			stm.bindLong(2, at.getType());
			stm.bindString(3, at.getName());
			stm.bindString(4, at.getDate());
			stm.bindString(5, at.getImgpath() == null ? "" : at.getImgpath());
			stm.bindString(6,
					at.getVediopath() == null ? "" : at.getVediopath());
			stm.bindString(7, at.getRecpath() == null ? "" : at.getRecpath());
			stm.execute();
			stm.clearBindings();
			stm.close();
		} catch (Exception e) {
			// will not happen
		}
	}

	public List<ContextInfo> getContextInfo() {
		String sql = " select _id,context,type,name,date,imgpath,vediopath,recpath from context_info ";
		Cursor cursor = null;
		List<ContextInfo> nums = null;
		try {
			cursor = db.rawQuery(sql, null);
			ContextInfo historie = null;

			if (cursor != null && cursor.moveToFirst()) {
				nums = new ArrayList<ContextInfo>();
				for (int i = 0; i < cursor.getCount(); i++) {
					historie = new ContextInfo();
					historie.setId(cursor.getInt(0));
					historie.setContext(cursor.getString(1));
					historie.setType(cursor.getInt(2));
					historie.setName(cursor.getString(3));
					historie.setDate(cursor.getString(4));
					historie.setImgpath(cursor.getString(5));
					historie.setVediopath(cursor.getString(6));
					historie.setRecpath(cursor.getString(7));
					nums.add(historie);
					cursor.moveToNext();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			cursor.close();
		}
		return nums;
	}

	public int getCount() {
		String sql = " select _id,tem_id,name,desc from context_info ";
		Cursor cursor = db.rawQuery(sql, null);
		try {
			if (cursor != null && cursor.moveToFirst()) {
				return cursor.getCount();
			}
		} catch (Exception e) {
			return 0;
		} finally {
			cursor.close();
		}
		return 0;
	}

	public void deleteAttribute(int id) {
		// db.delete("position_attribute", null, null);
		db.execSQL("delete from context_info where _id="+id);
	}

}
